package com.hu.core.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.hu.example.exception.DBException;

public class DBUtil {
    public static Connection getConnection() {
        try {
            Class.forName(PropertyUtil.getProperty("jdbc.driver"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Connection conn = null;
        try {
            conn = DriverManager.getConnection(PropertyUtil.getProperty("jdbc.url"), PropertyUtil.getProperty("jdbc.user"), PropertyUtil.getProperty("jdbc.pass"));
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DBException();
        }

        return conn;
    }

    public static void close(Connection conn, PreparedStatement pStatement, ResultSet rs) {
        try {
            if (null != rs) {
                rs.close();
            }

            if (null != pStatement) {
                pStatement.close();
            }

            if (null != conn) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void setAutoCommit(Connection conn, boolean autoCommit) {
        try {
            conn.setAutoCommit(autoCommit);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DBException();
        }
    }

    public static void commit(Connection conn) {
        try {
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DBException();
        }
    }

    public static void rollback(Connection conn) {
        try {
            conn.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DBException();
        }
    }
}
